<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import PageSkeleton from './components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeHot, getHomeCategoryAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import HotPanel from './components/HotPanel.vue'
import { useGuessList } from '@/composables'

// 轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类的数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()

  categoryList.value = res.result
    .map((item: CategoryItem) => {
      return item.name === '锦鲤' ? Object.assign(item, { name: '美食' }) : item
    })
    .filter((v) => v.name != '品牌')
}
// 获取猜你喜欢的组件的实例
const { guessRef, onScrollToLower } = useGuessList()
//获取热门推荐的数据
const hostList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHot()
  // console.log(res)
  hostList.value = res.result
}
// 控制是否在加载
const isLoading = ref(true)

// 控制下拉刷新时间的关闭
const isTriggered = ref(false)
// 自定义下拉刷新
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true

  // 重置猜你喜欢的数据
  guessRef.value?.resetData()

  await getHomeBannerData()
  await getHomeCategoryData()
  await getHomeHotData()

  await guessRef.value?.getmore()
  // 关闭动画
  isTriggered.value = false
}

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    scroll-y
    class="scoll-view"
    :refresher-triggered="isTriggered"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrollToLower"
  >
    <PageSkeleton v-if="!bannerList.length" />
    <template v-else>
      <!-- 自定义轮播图组件 -->
      <XTxSwiper :list="bannerList" />
      <!-- 分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hostList" />
      <!-- 猜你喜欢 -->
      <XTxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
/* #ifdef APP-PLUS */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scoll-view {
  flex: 1;
}
</style>
